﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using NoORM.Core.DbAcceess;

namespace NoORM.Core.DbMeta
{
    public class MetaContainer
    {
        private readonly Dictionary<string, ConnectionStringConfig> configs;
        private readonly MetaProviderBuilder metaProviderBuilder;


        public readonly Dictionary<string, Dictionary<string, List<FieldMeta>>> Metas;

        public MetaContainer(IOptions<Dictionary<string,ConnectionStringConfig>> configsOption, MetaProviderBuilder metaProviderBuilder)
        {
            this.configs = configsOption.Value;
            this.metaProviderBuilder = metaProviderBuilder;
            this.Metas = new Dictionary<string, Dictionary<string, List<FieldMeta>>>();
            foreach (var item in this.configs)
            {
                IMetaProvider metaProvider = this.metaProviderBuilder.Build(item.Value.ConnectionClassName);
                List<TableMeta> tables = metaProvider.GetTables(item.Value.ConnectionString);
                Dictionary<string, List<FieldMeta>> dicTable = new Dictionary<string, List<FieldMeta>>();
                foreach(TableMeta t in tables)
                {
                    List<FieldMeta> fields = metaProvider.GetFields(item.Value.ConnectionString, t.TableName);
                    dicTable.Add(t.TableName, fields);
                }
                this.Metas.Add(item.Key, dicTable);
            }
        }
    }
}
